"use strict";
var logData = [];

async function getData() 
{
  const response = await fetch('/getData');
  if (!response.ok) 
  {
      throw new Error('网络响应错误');
  }
  const data = await response.json();
  return data.diary;
}

window.onload = async function () 
{
  const logData = await getData();
  const filterButton = document.getElementById('filter-button');
  const warehouseTypeFilter = document.getElementById('warehouse-type-filter');
  const warehouseNameFilter = document.getElementById('warehouse-name-filter');
  const startTimeFilter = document.getElementById('start-time-filter');
  const endTimeFilter = document.getElementById('end-time-filter');
  const logTableBody = document.getElementById('log-table').getElementsByTagName('tbody')[0];
  renderLogs(logData);
  filterButton.addEventListener('click', function () {
      const typeFilterValue = warehouseTypeFilter.value.trim();
      const nameFilterValue = warehouseNameFilter.value.trim();
      const startDateTime = startTimeFilter.value;
      const endDateTime = endTimeFilter.value;
      let filteredData = logData;
      if (typeFilterValue !== "") 
      {
          filteredData = filteredData.filter(log => log.warehouse_name.includes(typeFilterValue));
      }
      if (nameFilterValue !== "") 
      {
          filteredData = filteredData.filter(log => log.device_code.includes(nameFilterValue));
      }
      if (startDateTime && endDateTime) 
      {
          filteredData = filteredData.filter(log => 
          {
              const logTime = new Date(log.create_date);
              const start = new Date(startDateTime);
              const end = new Date(endDateTime);
              return logTime >= start && logTime <= end;
          });
      }
      renderLogs(filteredData);
  });
  
  function renderLogs(data) 
  {
    logTableBody.innerHTML = "";
    console.log(data)
    data.forEach(log => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${log["warehouse_name"]}</td>
        <td>${log["device_code"]}</td>
        <td>${log["temp_data"]}</td>
        <td>${log["humi_data"]}</td>
        <td>${log["abnormal_temp"]}</td>
        <td>${log["abnormal_humi"]}</td>
        <td>${log["create_date"]}</td>
      `;
      logTableBody.appendChild(row);
    });
  }
};